package lg.minecraft.plugin.pokemonmenu.manager;

import com.cobblemon.mod.common.pokemon.Pokemon;
import lg.minecraft.plugin.cobblemoncore.util.BukkitNmsConverter;
import lg.minecraft.plugin.pokemonmenu.LGPokemonMenu;
import lombok.Setter;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

public class DisplayPokemonManger {

    public static final DisplayPokemonManger INSTANCE = new DisplayPokemonManger();

    private final Map<UUID, Long> cooldowns = new HashMap<>();
    private final TreeMap<Long, Pokemon[]> cache = new TreeMap<>();

    @Setter private long cooldownMillis;

    private DisplayPokemonManger() {}

    /**
     * 删除所有过期的冷却记录（时间早于当前时间 - 冷却时间）
     */
    public void purgeExpiredCooldowns() {
        long currentTime = System.currentTimeMillis();
        cooldowns.entrySet().removeIf(entry -> currentTime >= entry.getValue());
    }

    public void addCooldown(UUID uuid) {
        cooldowns.put(uuid, System.currentTimeMillis() + cooldownMillis);
    }

    public boolean hasCooldown(UUID uuid) {
        return cooldowns.containsKey(uuid);
    }

    public long getCooldown(UUID uuid) {
        return cooldowns.getOrDefault(uuid, 0L);
    }

    public int getRemainingCooldown(UUID uuid) {
        return (int) Math.max(-1, getCooldown(uuid) - System.currentTimeMillis());
    }

    // 添加键值对（时间戳作为 key）
    public long storePokemonWithTimestamp(Pokemon[] value) {
        Pokemon[] cloned = new Pokemon[value.length];
        for (int i = 0; i < value.length; i++) {
            if (value[i] != null) {
                cloned[i] = value[i].clone(false, BukkitNmsConverter.getRegistryAccess());
            }
        }

        long currentTime = System.currentTimeMillis() + LGPokemonMenu.getMainConfig().getDisplayTime();
        cache.put(currentTime, cloned);
        return currentTime;
    }

    // 删除所有小于等于某个时间戳的 key
    public void removeExpired(long currentTime) {
        TreeMap<Long, Pokemon[]> headMap = new TreeMap<>(cache.headMap(currentTime, true));
        for (Long key : headMap.keySet()) {
            cache.remove(key);
        }
    }

    // 删除所有小于等于当前时间戳的 key
    public void removeExpiredKeysBeforeNow() {
        removeExpired(System.currentTimeMillis());
    }

    // 获取某个时间戳对应的值
    public Pokemon[] get(long timestamp) {
        return cache.get(timestamp);
    }

}
